<!-- 商品管理->分类参数 -->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部的警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="selectedCateKeys" :options="catelist" :props="cateProps" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDiaVisible=true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableDta" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close='handleClose(i,scope.row)'>
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                  Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removeParamsId(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDiaVisible=true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableDta" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close='handleClose(i,scope.row)'>
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                  Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removeParamsId(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性对话框（两个共用的） -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDiaVisible" width="50%" @close="addDialogClosed">
      <!-- 主体表单 -->
      <el-form ref="addFormRef" :model="addForm" label-width="100px" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDiaVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog :title="'编辑'+titleText" :visible.sync="editDiaVisible" width="50%" @close="editDialogClosed">
      <!-- 主体表单 -->
      <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDiaVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 商品分类的数据
        catelist: [],
        // 级联选择框的配置对象
        cateProps: {
          expandTrigger: 'hover',
          value: 'cat_id', //选中的值
          label: 'cat_name', //看到的值
          children: 'children'
        },
        // 级联选择框的双向绑定的数组
        selectedCateKeys: [],
        // 被激活的页签
        activeName: 'many',
        // 动态参数的数据
        manyTableDta: [],
        // 静态数据的数据
        onlyTableDta: [],
        // 控件添加对话框的添加和隐藏
        addDiaVisible: false,
        // 添加参数的表单数据
        addForm: {
          attr_name: '',
        },
        // 添加表单的验证规则对象
        addFormRules: {
          attr_name: [
            { required: true, message: '请输入参数名称', tirgger: 'blur' }
          ],
        },
        // 控制编辑对话框的添加和隐藏
        editDiaVisible: false,
        // 修改的表单对象
        editForm: {},
      };
    },
    created() {
      this.getCateList()
    },

    components: {},

    computed: {
      // 如果按钮需要被警用，则返回true 
      isBtnDisabled() {
        if (this.selectedCateKeys.length !== 3) {
          return true
        }
        return false
      },
      // 当前选中的三级的分类id
      cateId() {
        if (this.selectedCateKeys.length === 3) {
          return this.selectedCateKeys[2]
        }
        return null
      },
      // 动态计算标题
      titleText() {
        if (this.activeName === 'many') return '动态参数'
        return '静态参数'
      }
    },

    // mounted: {},

    methods: {
      // 获取所有分类
      async getCateList() {
        const { data: res } = await this.$http.get('categories')
        if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
        this.catelist = res.data
      },
      // 级联选择框选中属性变换触发事件
      handleChange() {
        this.getParamsData()
      },
      // Tab页签点击触发函数
      handleTabClick() {
        this.getParamsData()
      },
      // 获取参数列表
      async getParamsData() {
        // 判断是否三级分类
        if (this.selectedCateKeys.length !== 3) {
          this.selectedCateKeys = []
          this.manyTableDta = []
          this.onlyTableDta = []
          return
        }
        // 根据所选分类的ID和所处的面板获取对应的参数
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
        // 把参数的样式从字符串变为数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的显示和隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })

        if (this.activeName === 'many') {
          this.manyTableDta = res.data
        } else {
          this.onlyTableDta = res.data
        }
      },
      // 监听添加对话框的关闭事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 点击按钮，添加参数
      addParams() {
        // 表单预验证
        this.$refs.addFormRef.validate(async valid => {
          // 用回调函数接受表单预验证的结果
          if (!valid) return
          const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 201) return this.$http.error('添加失败')
          this.$message.success('添加成功')
          this.addDiaVisible = false
          this.getParamsData()
        })
      },
      // 点击按钮，显示修改对话框
      async showEditDialog(attrId) {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
        if (res.meta.status !== 200) return this.$message.error('获取列表失败')
        this.editForm = res.data
        this.editDiaVisible = true
      },
      // 监听编辑对话框的关闭事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // 点击按钮，修改参数
      editParams() {
        // 表单预验证
        this.$refs.editFormRef.validate(async valid => {
          // 用回调函数接受表单预验证的结果
          if (!valid) return
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status !== 200) return this.$http.error('更新失败')
          this.$message.success('更新成功')
          this.editDiaVisible = false
          this.getParamsData()
        })
      },
      // 点击删除参数
      async removeParamsId(attrId) {
        const confirmResult = await this.$confirm('此操作将永久删除该参数，是否继续?', 'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 如果用户确认删除，则返回值为字符串 confirm
        // 如果用户取消删除，则返回值为字符串 cancel
        if (confirmResult !== 'confirm') return
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getParamsData()
      },
      // 保存文本框输入的的内容
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        // 当用户输入了正常内容
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrVals(row)
      },
      // 将attr_vals的操作，保存到数据库
      async saveAttrVals(row) {
        // 需要发起请求，保存这次操作
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status !== 200) return this.$message.error('修改标签失败！')
        this.$message.success('修改标签成功！')
      },
      // 点击按钮显示文本输入框
      showInput(row) {
        row.inputVisible = true
        // 让文本框自动获得焦点
        // $nextTick方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 点击关闭标签的响应事件
      handleClose(i, row) {
        row.attr_vals.splice(i, 1)
        this.saveAttrVals(row)
      }
    }
  }

</script>
<style lang='less' scoped>
  .cat_opt {
    margin: 15px 0;
  }

  .el-cascader {
    width: 300px !important;
  }

  .el-tag {
    margin: auto 5px;
  }

  .input-new-tag {
    width: 120px;
  }
</style>